import 'package:flutter/material.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:provider/provider.dart';
import 'package:wallpaper/components/AlertDialog/my_loading.dart';
import 'package:wallpaper/components/images/build_item.dart';
import 'package:wallpaper/components/placeholder/empty.dart';
import 'package:wallpaper/model/options_base.dart';
import 'package:wallpaper/providers/setting_provider.dart';
import 'dart:async';

import 'package:waterfall_flow/waterfall_flow.dart';

class ImageList extends StatefulWidget {
  final List imageList;
  final bool isLoading;
  final Function onImageBottomLoading;
  final Function onImageListRefresh;
  final bool isPC;
  final bool isMobile;
  final double emptyHeight;
  final int count;
  final bool isWaterfallFlow;
  final void Function()? onScrollStart;
  final void Function()? onScrollEnd;
  const ImageList({
    super.key,
    required this.imageList,
    required this.isLoading,
    required this.onImageBottomLoading,
    required this.onImageListRefresh,
    this.isPC = false,
    this.isMobile = false,
    this.emptyHeight = 0,
    this.count = 0,
    this.isWaterfallFlow = false,
    this.onScrollStart,
    this.onScrollEnd,
  });

  @override
  State<ImageList> createState() => _ImageListState();
}

class _ImageListState extends State<ImageList> {
  // 用于跟踪刷新操作的计时器
  Timer? _refreshTimer;
  // 标记组件是否已挂载
  bool _mounted = true;
  // 用于跟踪滚动到底部加载操作的计时器
  Timer? _loadMoreTimer;
  // 标记是否正在执行加载操作
  bool _isLoadingMore = false;

  // 实现 releaseRunningMemory 方法（原空方法）
  void releaseRunningMemory() async {
    if (!_mounted) return; // 组件销毁后不执行
    // 关键：清理内存中超出上限的缓存（由 CacheManager 自动判断）
    // 创建 DefaultCacheManager 实例
    final cacheManager = DefaultCacheManager();
    await cacheManager.emptyCache(); // 使用 emptyCache 方法替代 cleanupCache
  }

  @override
  void initState() {
    super.initState();
    _mounted = true;
  }

  @override
  void dispose() {
    _mounted = false;
    // 取消计时器避免内存泄漏
    _refreshTimer?.cancel();
    _loadMoreTimer?.cancel();
    releaseRunningMemory();
    // 关键：清空本地列表引用，帮助 GC 回收
    widget.imageList.clear(); // 注意：若其他地方也引用该列表，需谨慎（建议用副本）
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final SettingProvider setting = Provider.of<SettingProvider>(context);
    return RefreshIndicator(
        child: NotificationListener<ScrollNotification>(
          // 使用NotificationListener监听滚动事件
          onNotification: (ScrollNotification scrollInfo) {
            double bottomDistance =
                scrollInfo.metrics.maxScrollExtent - scrollInfo.metrics.pixels;
            // 检测是否滚动到底部附近
            if (scrollInfo is ScrollUpdateNotification &&
                bottomDistance <= 200) {
              if (widget.isLoading || _isLoadingMore) {
                return false; // 如果正在加载则不触发加载
              }

              // 立即触发加载
              _isLoadingMore = true;
              widget.onImageBottomLoading();

              // 设置计时器，在1秒后允许再次触发加载
              _loadMoreTimer?.cancel();
              _loadMoreTimer = Timer(Duration(milliseconds: 1000), () {
                if (_mounted) {
                  _isLoadingMore = false;
                }
              });
            }
            // 监听滚动停止
            if (scrollInfo is ScrollEndNotification) {
              releaseRunningMemory();
              widget.onScrollEnd?.call();
            }
            // 监听滚动开始
            if (scrollInfo is ScrollStartNotification) {
              widget.onScrollStart?.call();
            }
            return false; // 返回false以允许事件继续冒泡
          },
          child: RepaintBoundary(
            child: Padding(
              padding: EdgeInsets.all(setting.padding),
              child: _buildShowBody(setting.padding),
            ),
          ),
        ),
        onRefresh: () {
          widget.onImageListRefresh();
          // 使用 Completer 来正确处理异步操作
          final completer = Completer<void>();

          // 取消之前可能存在的计时器
          _refreshTimer?.cancel();

          // 创建新的计时器
          _refreshTimer =
              Timer(Duration(milliseconds: OptionsBase().refreshTime), () {
            // 确保组件仍然挂载再完成刷新操作
            if (_mounted) {
              completer.complete();
            }
          });

          return completer.future;
        });
  }

  Widget _buildShowBody(double padding) {
    final theme = Theme.of(context).colorScheme;
    if (widget.isLoading && widget.imageList.isEmpty) {
      return const Center(child: CircularProgressIndicator());
    } else if (widget.imageList.isEmpty) {
      return Empty();
    } else {
      return CustomScrollView(
        physics: const BouncingScrollPhysics(
          parent: AlwaysScrollableScrollPhysics(),
        ),
        cacheExtent: 300,
        slivers: [
          SliverToBoxAdapter(
            child: SizedBox(height: widget.emptyHeight),
          ),
          // 核心改造：SliverPadding 包裹 SliverWaterfallFlow（替代原 SliverGrid）
          SliverPadding(
            padding: const EdgeInsets.only(top: 5),
            // 瀑布流核心组件：SliverWaterfallFlow
            sliver: SliverWaterfallFlow(
              // 网格代理：控制列数、间距、动态宽高比
              gridDelegate: SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
                crossAxisCount: widget.isPC
                    ? OptionsBase().horizontalColumns(context)
                    : OptionsBase().imageColumns(context),
                crossAxisSpacing: padding,
                mainAxisSpacing: padding,
              ),
              // 子项代理
              delegate: SliverChildBuilderDelegate(
                (context, index) {
                  final image = widget.imageList[index];
                  // 计算宽高比
                  double aspectRatio = widget.isPC ? 1.7 : 0.75;
                  if (widget.isWaterfallFlow &&
                      image.width != null &&
                      image.height != null) {
                    aspectRatio = image.width! / image.height!;
                  }
                  return AspectRatio(
                    aspectRatio: aspectRatio,
                    child: BuildItem(
                      key: ValueKey(image.smallPath),
                      imgs: widget.imageList,
                      index: index,
                    ),
                  );
                },
                childCount: widget.imageList.length, // 子项数量（图片列表长度）
                addAutomaticKeepAlives: false, // 关键：关闭自动保活，释放不可见组件
                addRepaintBoundaries: false, // 辅助：减少渲染层内存占用
              ),
            ),
          ),
          SliverToBoxAdapter(
            child: Padding(
              padding: const EdgeInsets.all(3.0),
              child: SizedBox(
                height: 30,
                child: Center(
                  child: widget.isLoading
                      ? MyLoading(type: 1, size: 30)
                      : Text(
                          '~ 已经到底了 ~',
                          style: TextStyle(
                            color: theme.onSurface.withAlpha(90),
                          ),
                        ),
                ),
              ),
            ),
          )
        ],
      );
    }
  }
}
